home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5834 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.2 KB

  1. Path: raffles.technet.sg!usenet
  2. From: cheehui <cheehui@aztech.com.sg>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Turbo C 3.0 - arithmetic in defines
  5. Date: Fri, 16 Feb 1996 09:57:42 +0800
  6. Organization: PMO
  7. Message-ID: <3123E496.145B@aztech.com.sg>
  8. References: <4fqgkf$iqd@ccshst05.cs.uoguelph.ca> <4fre9v$kcs@news.nstn.ca> <4fvphq$t06@druid.borland.com>
  9. NNTP-Posting-Host: 202.42.226.169
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b6a (Win95; I)
  14.  
  15. >thay@uoguelph.ca (Toby K Hay) wrote:
  16. >#define var1 16
  17. >#define var2 485
  18. >#define var3 ((var2-1)/var1)+1
  19. >int main(void)
  20. >       {
  21. >       printf("\n%i    %i    %i    %i",var1,var2,var3,var1*var3);
  22. >       return 0;
  23. >       }
  24. >
  25. >Output from this is '16 485 31 481', not '16 485 31 496' as I should have
  26. >expected.  That is, var3 is calculated correctly in its #define, but the
  27. >var1*var3 in the printf() statement is not calculated correctly.  Where
  28. >am I going wrong?
  29.  
  30. Try this instead :
  31. #define var3 ((var2-1)/var1+1)
  32.  
  33. The reason for the failure is precedence.
  34. The compiler takes the last variable as:
  35.  
  36. var1 * (var2-1)/var1+1
  37.  
  38. which is (var1*(var2-1)/var1)+1 which gives 16*30 +1 = 481
  39.  
  40. QED.
  41.  
  42. Regards
  43. Chee Hui :)
  44. e-mail:cheehui@aztech.com.sg
  45.